Page({
  data: {
    mobile: "17711111111",
    code: "",
    countDownVisible: false, //控制倒计时显示与隐藏
  },

  onLoad() {},

  //显示倒计时
  countDownChange(ev) {
    // console.log(ev.detail)
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.seconds > 0 || ev.detail.minutes === 1,
    });
  },

  //校验手机号
  verifyMobile() {
    const reg = /^1[3-9]\d{9}$/; //正则

    const flag = reg.test(this.data.mobile.trim()); //校验结果

    if (!flag) wx.utils.toast("手机格式有误");

    return flag;
  },

  //校验验证码
  verifyCode() {
    // 验证码为6位数字
    const reg = /^\d{6}$/;
    // 验证验证码
    const valid = reg.test(this.data.code.trim());
    // 验证结果提示
    if (!valid) wx.utils.toast("请检查验证码是否正确!");
    // 返回验证结果
    return valid;
  },

  //获取验证码
  async getCode() {
    //校验手机号
    if (!this.verifyMobile()) return;

    //开启倒计时
    this.setData({ countDownVisible: true });

    await wx.http.get(`/v1_0/sms/codes/${this.data.mobile}`);

    wx.utils.toast("获取验证码成功");
  },

  //提交
  async submitForm() {
    //提交之前的校验
    if (!this.verifyMobile()) return;
    if (!this.verifyCode()) return;

    // console.log(1)
    const { code, mobile } = this.data;
    const { data } = await wx.http({
      method: "post",
      url: "/v1_0/authorizations",
      header: { ContentType: "application / json" },
      data: { mobile, code },
    });

    console.log(data);
    //存token
    getApp().setToken(data.token);

    //跳转原来的页面
    wx.redirectTo({
      url: "",
    });
  },
});
